/**
 * Created by sxx on 2017/5/6.
 */
import "./index.less";
import httpurl from "../../../unit/common/js/httpurl";
import { splrTyp } from "../config.js";
import UserBasicInfoTpl from './tmpl/user_basic_info.handlebars';
import AptListTpl from './tmpl/attachment.handlebars';
import bankListTpl from './tmpl/bank_list.handlebars';
import matInfoTpl from './tmpl/mat_info.handlebars';
import searchMatTpl from './tmpl/search_mat.handlebars';
jQuery(document).ready(function() {

    App.init();
    let token = sessionStorage.getItem('token');

    let splrId = httpurl.uri.params.id;
    let canClick = true;

    const ApplyDetail = {
        comParm: '',
        regionList: '',
        aptSplrId: '',
        aptTempId: '',
        matList: [],
        prodList: [],
        init: function() {
            this.getData()
                .then(this.getRegionInfo)
                .then(this.getComParms)
                .then(this.renderBasicInfo)
                .then(this.renderAttachment);
            this.getAdtTemp()
                .then(this.setAptTempId)
                .then(this.appendMatItem)
                .then(this.bindEvent);
        },
        // 绑定事件
        bindEvent: function() {
            const self = ApplyDetail;

            $('.J_aptTempDownload').click(() => {
                window.location.href = HOST_ADDR + '/cpmp/chkTab/download/1';
            });

            $('.J_mat-list').on('change', '.J_matCod', (e) => {
                let $item = $(e.target),
                    $curItem = $($item[0].options[$item[0].selectedIndex]),
                    unit = $curItem.data('unit'),
                    type = $curItem.data('type');
                console.log($curItem.closest('.mat-item').find('.J_matTyp'));
                $curItem.closest('.mat-item').find('.J_matTyp').val(type);
                $curItem.closest('.mat-item').find('.J_matUnt').val(unit);

            });
            $('.J_uploadAptTemp').click(() => {
                self.uploadAptTemp();
            });
        },
        //上传考核表
        uploadAptTemp: function() {
            const self = ApplyDetail;
            let file = $('.J_file')[0].files[0];
            if (!file) {
                alert('请先上传考察表');
                return;
            }
            let formData = new FormData();
            formData.append('file', file);
            console.log(formData);
            $.ajax({
                url: HOST_ADDR + '/cpmp/chkTab/upload',
                type: 'post',
                cache: false,
                headers: {
                    'chkTyp': 'admt',
                    'id': self.aptTempId,
                    'splrId': splrId,
                    'access_token': token,
                    'login_type': 'ums'
                },
                data: formData,
                processData: false,
                contentType: false,
                success: function(resp) {
                    if (resp.success) {
                        self.aptSplrId = resp.data;
                        alert('上传文件成功');
                    } else {
                        alert(resp.msgInf);
                    }

                },
                error: function(err) {
                    console.log(err);
                }

            })
        },
        // 获取地区信息
        getRegionInfo: function(data) {
            const self = ApplyDetail;
            return new Promise((resolve, reject) => {
                if (self.regionList) {
                    resolve(data);
                }

                const regionList = localStorage.getItem('regionList');
                if (regionList) {
                    self.regionList = JSON.parse(regionList);
                    resolve(data);
                } else {
                    $.ajax({
                        url: HOST_ADDR + '/cpmp/region/region_all',
                        type: 'get',
                        dataType: 'json',
                        contentType: "application/json",
                        success: function(resp) {
                            localStorage.setItem('regionList', JSON.stringify(resp));
                            self.regionList = resp;
                            resolve(data);

                        },
                        error: function(err) {
                            console.log(err);
                        }
                    });

                }
            });
        },
        appendMatItem: function() {
            const self = ApplyDetail;
            let matHtml = searchMatTpl({});
            $('.J_mat-search').append(matHtml);
            $('.chzn-single').click(function() {
                $(this).toggleClass('chzn-single-with-drop');
                $('#selWNF_chzn').toggleClass('chzn-container-active');
                if ($(this).hasClass('chzn-single-with-drop')) {
                    $('.chzn-drop').css('left', '0px');
                } else {
                    $('.chzn-drop').css('left', '-9999px');
                }
            });
            $('.chzn-search').on('keyup', 'input', function() {
                let val = $(this).val();
                if(val==''){
                    $('.chzn-results').html('');
                    return;
                }
                let data = {
                    "matDesc": val
                };
                $.ajax({
                    url: HOST_ADDR + '/cpmp/mat/matList/1/20',
                    type: 'post',
                    dataType: 'json',
                    data: JSON.stringify(data),
                    contentType: "application/json",
                    success: function(resp) {
                        if (resp.success) {
                            if (resp.data && resp.data.list.length) {
                                let result = '';
                                $.each(resp.data.list,function(index,item){
                                    if (index < 10) {
                                        result = result + `<li class="active-result" data-unt="${item.unt}" data-cod="${item.matCod}" data-typ="${item.matTyp}" data-id="${item.matId}" data-desc="${item.matDesc}">${item.matTyp}(${item.matDesc})<div class="btn mini J_addMat">添加</div></li>`;
                                    }
                                });
                                $('.chzn-results').html(result);
                            } else {
                                $('.chzn-results').html(`暂无搜索结果`);
                            }
                        }
                    },
                    error: function(err) {
                        console.log(err);
                    }
                });
            });
            $('.chzn-results').on('click', '.J_addMat', function(e) {
                console.log('addMat');
                let id = $(e.target).closest('.active-result').data('id');
                let matTyp = $(e.target).closest('.active-result').data('typ');
                let matNam = $(e.target).closest('.active-result').data('desc');
                let matUnt = $(e.target).closest('.active-result').data('unt');
                let matCod = $(e.target).closest('.active-result').data('cod');
                // let cnty = $(e.target).data('cnty');
                $('.chzn-single').removeClass('chzn-single-with-drop');
                $('.chzn-single span').text(`${matTyp}(${matNam})`);
                $('#selWNF_chzn').removeClass('chzn-container-active');
                $('.chzn-drop').css('left', '-9999px');
                self.matList.push({ id, matTyp, matNam, matUnt, matCod });
                console.log(self.matList);
                self.renderMatList();
            });
        },

        renderMatList() {
            const self = ApplyDetail;
            let afterRpeatList = self.toRpeat(self.matList);
            console.log(afterRpeatList);
            self.matList = afterRpeatList;
            if (self.matList.length > 0) {
                $.each(self.matList,function(index,item){
                    if (self.prodList.indexOf(item.matTyp) == -1) {
                        self.prodList.push(item.matTyp);
                    }
                });
                $('.J_mat-list').html(matInfoTpl({ matList: self.matList })).removeClass('hidden');
                $('.J_delete_mat').click(function(e) {
                    let id = $(e.target).data("id");
                    self.deleteMat(id);
                });
            } else {
                $('.J_mat-list').html({}).addClass('hidden');
            }
        },
        deleteMat(id) {
            const self = ApplyDetail;
            let arr = new Array();
            $.each(self.matList,function(index,item){
                if (item.id !== id) {
                    arr.push(item);
                }
            });
            self.matList = arr;
            self.renderMatList();
        },
        //去重复
        toRpeat(arry) {
            const self = ApplyDetail;
            var arr = new Array();
            for (var i = 0; i < arry.length; i++) {
                if (i == 0) {
                    arr.push(arry[i]);
                } else {
                    //是否包含
                    var status = self.isCot(arr, arry[i].id);
                    //不包含
                    if (status == false) {
                        console.log('status?');
                        arr.push(arry[i]);
                    }
                }
            }
            return arr;
        },
        //判断是否包含
        isCot(arr, id) {
            var flag = false;
            for (var i = 0; i < arr.length; i++) {
                console.log(arr[i]);
                console.log(id);
                if (arr[i].id == id) {
                    flag = true;
                }
            }
            console.log(flag);
            return flag;
        },

        getComParms(data) {
            const self = ApplyDetail;
            return new Promise((resolve, reject) => {
                const parmTyps = 'CPN_NTR,SPLR_TYP,IDST_TYP,GRUP_ACNT_GRUP';
                const url = HOST_ADDR + '/cpmp/comParm/getByParmTyps/' + parmTyps;
                $.ajax({
                    url: HOST_ADDR + '/cpmp/comParm/getByParmTyps/' + parmTyps,
                    type: 'get',
                    dataType: 'json',
                    //headers:{
                    //    'access_token': token,
                    //    'login_type': 'splr'
                    //},
                    contentType: 'application/json',
                    success: function(resp) {
                        self.comParm = resp;
                        resolve(data);
                    },
                    error: function(err) {
                        console.log(err);
                    }
                })
            })
        },
        //获取数据
        getData: function() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: HOST_ADDR+'/cpmp/splrMng/splr/'+splrId,
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'access_token': token,
                        'login_type': 'ums'
                    },
                    contentType: "application/json",
                    success: function(resp) {
                        if (resp.success && resp.msgCod === 'S0002') {
                            console.log(resp);
                            resolve(resp);
                        } else {
                            alert(resp.msgInfo);
                        }
                    },
                    error: function(err) {
                        console.log(err);
                    }

                });

            });
        },

        // 获取供应商考核表信息
        getAdtTemp: function() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: HOST_ADDR+'/cpmp/splrAdt/adtTempForType/',
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'type': 'aply',
                        'access_token': token,
                        'login_type': 'ums'
                    },
                    contentType: "application/json",
                    success: function(resp) {
                        if (resp.success && resp.msgCod === 'S0002') {
                            console.log(resp);
                            resolve(resp);
                        } else {
                            alert(resp.msgInfo);
                        }
                    },
                    error: function(err) {
                        console.log(err);
                    }

                });
            })
        },

        setAptTempId: function(rsp) {
            const self = ApplyDetail;
            self.aptTempId = rsp.data.tempId;
            console.log('aptTempId: ' + self.aptTempId);
        },
        // 渲染详情

        // 渲染用户基本信息
        renderBasicInfo(rsp) {
            const self = ApplyDetail;
            return new Promise((resolve, reject) => {
                let data = rsp.data;
                data.ptnrTypFmt = splrTyp[data.classification];
                if (!self.comParm) {
                    self.getComParms().then(() => {
                        data = self.formatData(data);
                        let basicInfoHtml = UserBasicInfoTpl({ data });
                        $('#J_basicInfo').html(basicInfoHtml);
                    })
                } else {
                    data = self.formatData(data);
                    let basicInfoHtml = UserBasicInfoTpl({ data });
                    $('#J_basicInfo').html(basicInfoHtml);
                }
                let aptList = data.splrApts;
                if (aptList.length > 0) {
                    $.each(aptList,function(index,item){
                        if (item.aptVal) {
                            item.addrFmt = HOST_ADDR + '/' + item.aptVal;
                        }
                    });
                    let aptListHtml = AptListTpl({ aptList });
                    $('.J_attachment').html(aptListHtml).closest('.row-fluid').removeClass('hidden');
                }
                let bankList = data.splrBnkAcnts;
                if (bankList.length > 0) {
                    let bankListHtml = bankListTpl({ bankList });
                    $('.J_bank').html(bankListHtml).closest('.row-fluid').removeClass('hidden');
                }
                resolve(rsp);
            });
        },
        renderAttachment(rsp) {
            return new Promise((resolve, reject) => {
                if (rsp.data.splrApts) {
                    console.log(rsp.data.splrApts);
                    $.each(resp.data.splrApts,function(index,item){
                        console.log(HOST_ADDR + '/' + item.aptVal);
                    })
                }
            })
        },
        // 处理数据
        formatData(data) {
            let self = ApplyDetail;
            console.log(self.regionList);
            data.hasCreditCode = data.hasCreditCode == '1' ? '是' : '否';
            data.contact = data.contact ? data.contact : '';
            data.fullAddr = data.rgstAddr;
            let region, city, district;
            let regDate = new Date(data.regTim);
            if (data.region) {
                data.region = $.trim(data.region);
                region = self.regionList[data.region].name;
                city = data.city ? self.regionList[data.region].cities[$.trim(data.city)].name : '';
                district = (data.city && data.district) ? self.regionList[data.region].cities[$.trim(data.city)].towns[$.trim(data.district)].name : '';
                data.fullAddr = region + city + district + (data.rgstAddr ? data.rgstAddr : '');
            }
            console.log(region);
            data.fullTel = '';
            data.fullFax = '';
            if(data.telEx || data.telephone){
                if(data.telEx && data.telephone){
                    data.fullTel = data.telEx + ' - ' + data.telephone;
                }else{
                    data.fullTel = data.telEx ? data.telEx : data.telephone;
                }
            }
            if(data.faxEx || data.fax){
                if(data.faxEx && data.fax){
                    data.fullFax = data.faxEx + ' - ' + data.fax;
                }else{
                    data.fullFax = data.faxEx ? data.faxEx : data.fax;
                }
            }
            data.regTimFmt = `${regDate.getFullYear()}年${regDate.getMonth()+1}月${regDate.getDate()}日`;
            $.each(self.comParm.data.IDST_TYP,function(index,item){
                if (item.parmCod === data.idst1) {
                    console.log(item);
                    data.idst1 = item.parmVal;
                }
                if (item.parmCod === data.idst2) {
                    console.log(item);
                    data.idst2 = item.parmVal;
                }
            });
            $.each(self.comParm.data.SPLR_TYP,function(index,item){
                if (item.parmCod == data.ptnrTyp) {
                    data.ptnrTyp = item.parmVal;
                }
            });
            $.each(self.comParm.data.CPN_NTR,function(index,item){
                if (item.parmCod == data.cpnNtr) {
                    data.cpnNtr = item.parmVal;
                }
            });

            return data;
        },

    };

    ApplyDetail.init();
    $('.J_pass').off().on('click', function() {
        let data = {};
        if (canClick == true) {
            canClick = false;
            data.matIds = [];
            if(ApplyDetail.matList.length){
                let SplrMats = ApplyDetail.matList;
                for(var i=0;i<SplrMats.length;i++){
                    data.matIds.push(SplrMats[i].matCod);
                }
            }
            if (ApplyDetail.aptSplrId) {
                data.chkIds = [ApplyDetail.aptSplrId];
            }else{
                data.chkIds = [];
            }
            data.splrId = splrId;
            data.remark = $(".J_memo").val();
            data.prodList = ApplyDetail.prodList.join(",");
            $.ajax({
                url: HOST_ADDR + `/cpmp/splrAdt/admt`,
                type: 'post',
                dataType: 'json',
                data: JSON.stringify(data),
                headers: {
                    'access_token': token,
                    'login_type': 'ums'
                },
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        alert('注册审核申请成功');
                        canClick = true;
                        location.href = 'supplier_apply_list.html';
                    } else {
                        canClick = true;
                        alert(resp.msgInf);
                        location.href = 'supplier_apply_list.html';
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        }
        console.log('clicked');
    })

});